﻿using CSCSN.EntitiyModels;
using CSCSN.ORM;
using CSCSN.ViewModels.RoleAndUser;
using CSCSN.ViewModelServices;
using CSCSN.WebApplication.Verification;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Policy;
using System.Threading.Tasks;

namespace CSCSN.WebApplication.Controllers
{
    /// <summary>
    /// 系统登录相关的处理
    /// </summary>
    public class AccountController : Controller
    {

        #region 数据上下文实例
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly IViewModelService<ApplicationUser, ApplicationUserVM> _service;
        private readonly CsDbContext db;
        //private int Error=0;

        public AccountController(
             SignInManager<ApplicationUser> singInManager,
             IViewModelService<ApplicationUser, ApplicationUserVM> service,
             CsDbContext logger
            )
        {
            this._signInManager = singInManager;
            this._service = service;
            db = logger;
        }
        #endregion

        #region 登录

        [HttpGet]
        public IActionResult Login(string returnUrl)
        {
            returnUrl = returnUrl ?? Url.Content("/Home/Index");

            return View(new LoginVM() { ReturnUrl = returnUrl });
        }
     
        public async Task<IActionResult> Login(LoginVM loginVM, ApplicationUser applicationUser)
        {
           
            if (ModelState.IsValid)
            {
                //通过接口查找用户名
                var user = await _service.EntityRepository.ApplicationUserManager.FindByNameAsync(loginVM.UserName);
                if (user != null)
                {

                    if (user.LockoutEnabled)
                    {
                        if (loginVM.Verify==securityCode_input)
                        {

                      
                        // 登录系统
                                var result = await _signInManager.PasswordSignInAsync(user, loginVM.Password, loginVM.RememberMe, lockoutOnFailure: false);
                                if (result.Succeeded == true)
                                {
                                var userData = _service.EntityRepository.EntitiesContext.ApplicationUserDatas.Where(s => s.ApplicationUsers.UserName == loginVM.UserName).FirstOrDefault();
                                if (userData == null)//如果用户没有填写个人信息
                                {
                                    return RedirectToAction("Creat", "PersonCentrel",new {ID=user.Id});
                                }
                                return RedirectToAction("Index", "Home");
                                }           
                        }
                        else
                        {
                          ModelState.AddModelError("", "验证码错误，请重新输入");
                           return View(loginVM);
                        }
                    }
                }        
            }
                ViewData["LoginStatusString"] = "用户名或者密码错误";
                return View(loginVM);                   
        }
    


        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        public IActionResult LoginVerify()
        {
            return View();
        }

        //public async Task<IActionResult> LoginVerify(LoginVM loginVM, string name)
        //{
        //    if (securityCode_input == name)
        //    {
        //        var result = await _signInManager.PasswordSignInAsync(user, loginVM.Password, loginVM.RememberMe, lockoutOnFailure: false);
        //        if (result != null)
        //        {
        //            if (!String.IsNullOrEmpty(loginVM.ReturnUrl))
        //                return Redirect(loginVM.ReturnUrl);
        //            else
        //                return RedirectToAction("Index", "Home");
        //        }
        //        else
        //        {
        //            ViewData["LoginStatusString"] = "用户名或者密码错误。";
        //            return RedirectToAction("Index", "Home");
        //        }
        //    }
        //}
        #endregion

        #region 退出
        /// <summary>
        /// 注销，注销之后统一处理返回至系统首页
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction("Index", "Home");
        }
        #endregion

        #region 修改密码

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ForgetPwd()
        {
            return View();
        }
        public async Task<IActionResult> ForgetPwd(ChangePasswordViewModel changePassword)
        {
            var ActiveUser = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).First();
            if (changePassword.NewPassword == changePassword.ConfirmPassword)
            {
                var result = await _service.EntityRepository.ApplicationUserManager.ChangePasswordAsync(ActiveUser, changePassword.OldPassword, changePassword.NewPassword);
                if (result.Succeeded == true)
                {
                    return RedirectToAction("Logout", "Account");
                }
                else
                {
                    ModelState.AddModelError("", "当前密码错误");
                }

            }
            else
            {
                ModelState.AddModelError("", "两次密码输入不一致");
            }
            return View();
        }
        #endregion

        #region 图形验证    
        /// <summary>
        /// 生成机械验证码
        /// </summary>
        static string securityCode_input = "";
        public ActionResult GetSecurityCode()
        {
            Verify code = new Verify();
            securityCode_input = code.CreateValidateCode(4);
            byte[] buf = code.CreateValidateGraphic(securityCode_input);
            return File(buf, "image/Jpeg");
        }
        #endregion

        #region 账号注销
        [HttpGet]
        public IActionResult RemoveUser()
        {
            return View();

        }
        public async Task<IActionResult> RemoveUser(ChangePasswordViewModel changePasswordView)
        {
            var ActiveUser = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).First();
            var result = await _service.EntityRepository.ApplicationUserManager.CheckPasswordAsync(ActiveUser, changePasswordView.OldPassword);
            if (result == true)
            {
                db.Remove(ActiveUser);
                db.SaveChanges();
                return RedirectToAction("Logout", "Account");
            }
            else

            {
                ModelState.AddModelError("", "当前密码错误");
            }
            return View();
        }
        #endregion


    }



}
